<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/12/29
 * Time: 13:41
 */

class User extends CI_Controller
{
    /*
     * 构造函数  初始化
     */
    public function __construct()
    {
        parent::__construct();
        $this->load->library('ResponseUtil', null, 'resp');
        $this->load->model("usermodel");
        $this->load->model("namesmodel");
        $this->load->library('Common', null, 'common');
    }

    /**
     * 处理用户授权登录
     * 1.根据code，encryptedData，iv解密用户信息
     * 2.根据unionId查找是否已经有改用户信息，有则把openid加入到用户表中，没有则新插入用户
     * 3.判断用户是否付19.8,记录付的次数
     * 3.返回用户信息
     */
    public function php_getUserInfo()
    {
        $this->load->library('WxappLibrary', null, 'wl');

        $params = json_decode($this->input->post('param'), true);

        $userInfo = $this->wl->encryptUserInfo($params['code'], $params['encryptedData'], $params['iv']);//, $params['encryptedData'], $params['iv']


        if (!$userInfo)
            $this->resp->fail("服务：获取用户信息失败");
        $data = array(
            "nickname" => $userInfo['nickName'],
            "openid" => $userInfo['openId'],  //"openId"    =>  $userInfo,
            "avatarUrl" => $userInfo['avatarUrl'],
            "unionid" => $userInfo['unionId'],
        );

        $result = $this->usermodel->queryUserByUnionId($data['openid']);

        if ($result) {
            $userId = $result['id'];
            $updateData = array();
            if (!$result['openid'])
                $updateData['openid'] = $data['openid'];
            if (stristr($result['avatarUrl'], 'https://wx.qlogo.cn/'))
                $updateData['avatarUrl'] = $data['avatarUrl'];
            $updateData['nickname'] = $data['nickname'];
            $updateData['refresh'] = $result['refresh'];
            $updateData['havecount'] = $result['havecount'];
            $updateData['testresult'] = 11;
            if (count($updateData))
                $this->usermodel->updateUserinfo($updateData, $userId);
        } else {
            $data['refresh'] = 3;
            $data['haveCount'] = 30;
            $data['testresult'] = 11;
            $userId = $this->usermodel->insertUserinfo($data);
        }

        if (!$userId)
            $this->resp->fail("服务：服务器器异常");
        $userInfos = $this->usermodel->queryUserById($userId);
        $row = $this->usermodel->isTip($data['openid']);
        $tipCount = $row['num'];

        $this->resp->success(array('userinfo' => $userInfos, 'tipCount' => $tipCount));
    }

    /**
     * 获取所有文章
     */
    public function php_getAllArt(){
        $artlist = $this->usermodel->getAllArt();
        for($i=0;$i<count($artlist);$i++){
            $date = $artlist[$i]['createtime'];
            $res = $this->formatDate($date);
            $artlist[$i]['createtime']=$res;
        }
        $this->resp->success($artlist);
    }
    /**
     * 获取最新5条文章
     */
    public function php_getArtList(){

        $artlist = $this->usermodel->getArtList();
        for($i=0;$i<count($artlist);$i++){
            $date = $artlist[$i]['createtime'];
            $res = $this->formatDate($date);
            $artlist[$i]['createtime']=$res;
        }
        $this->resp->success($artlist);

    }
    /**
     * 获取文章信息
     */
    public function php_getArt()
    {
        date_default_timezone_set('PRC');

        $artid = $this->input->get('artid');
        $this->load->model("usermodel");
        $art = $this->usermodel->getArtById($artid);
        $art['createtime'] = date("Y-m-d",strtotime($art['createtime']));
        $this->resp->success($art);
    }

    /**
     * 收集formID（用于发送小程序模版消息推送）
     */
    public function php_formIdCollect()
    {
        $params = json_decode($this->input->post('param'), true);
        $data = array(
            'formid' => $params['formid'],
            'openid' => $params['openid']
        );
        $formId = $this->usermodel->addFormId($data);
        $this->resp->success(array('formId' => $formId));
    }

    /**
     * 添加浏览记录
     */
    public function php_addSeeHistory()
    {
        $params = json_decode($this->input->post('param'), true); //userid  content type
        $this->usermodel->addSeeHistory($params['userid'], $params['type'], $params['lastname'], $params['firstname'], $params['articid'], $params['sex'], $params['birthdaytime']);
    }

    /**
     * 获取浏览记录
     */
    public function php_getSeeHistory()
    {
        $params = json_decode($this->input->post('param'), true);
        $historyList = $this->usermodel->getSeeHistory($params['userid'], $params['page']);

        $this->resp->success($historyList);
    }

    /**
     * 生成图片
     */
    public function php_getPic()
    {
        $params = json_decode($this->input->post('param'), true);
        $tickid = $params['tickid'];
        $openid = $params['openid'];
        $data = '{
            "path":"pages/pytp/pytp?tickid=' . $tickid . '&shareUserOpenId='. $openid .'",
            "width": 120   
        }';

        $accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxde194c3ecffe62ec&secret=05f82e8c24bdb173701ecdf155d4debf";
        $accessToken = json_decode($this->common->curl($accessTokenUrl, false), true)['access_token'];
        $qrCodeUrl = "https://api.weixin.qq.com/wxa/getwxacode?access_token=$accessToken";
        $stream = $this->common->curl($qrCodeUrl, true, $data);
        file_put_contents("./images/qm$tickid.png", $stream);
        $this->resp->success(array('ticketid' => $tickid));

    }

    /**
     *
     */
    public function formatDate($date)
    {
        date_default_timezone_set('PRC');
        $date = date("m-d", strtotime($date));
        return $date;
    }
    public function csss()
    {
        echo 1;
    }
    public function php_test()
    {
        $page = 22;
        $count = 12;
        $num = $page%$count;

        $this->resp->success(array('ticketid' => $num));
    }
}
